package com.aiapphub.BaseCode.filter;

import com.aiapphub.BaseCode.entity.SsoUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.aiapphub.BaseCode.common.ResponseResult;
import com.aiapphub.BaseCode.constants.AppHttpCodeEnum;
import com.aiapphub.BaseCode.utils.JwtUtil;
import com.aiapphub.BaseCode.utils.RedisCache;
import com.aiapphub.BaseCode.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;


@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ObjectMapper objectMapper; // 推荐使用 ObjectMapper 进行 JSON 处理

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中的 token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            // 说明该接口不需要登录，直接放行
            filterChain.doFilter(request, response);
            return;
        }

        // 解析获取 userid
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            // 打印异常日志并返回错误信息给客户端
            e.printStackTrace();
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_INVALID, "TOKEN令牌无效");
            WebUtils.renderString(response, objectMapper.writeValueAsString(result));
            return;
        }

        String userId = claims.getSubject();
        // 从 Redis 缓存中获取 JSON 字符串并反序列化为 User 对象
        String userJsonFromCache = redisCache.getCacheObject("userInfo:" + userId);
        SsoUser user = objectMapper.readValue(userJsonFromCache, SsoUser.class);

        // 如果获取不到
        if (Objects.isNull(user)) {
            // 说明登录过期，提示重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, objectMapper.writeValueAsString(result));
            return;
        }

        // 存入 SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, null);
        System.out.println("authenticationToken==============================:" + authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        
        filterChain.doFilter(request, response);
    }
}
